package cz.gelion.shylock.invoice.web.subj

import org.apache.wicket.behavior.Behavior
import cz.gelion.shylock.invoice.web.ShylockInvoicePage
import org.apache.wicket.request.component.IRequestablePage
import org.apache.wicket.markup.html.WebMarkupContainer
import org.apache.wicket.markup.html.list.ListItem
import org.apache.wicket.markup.html.list.ListView
import org.apache.wicket.model.LoadableDetachableModel
import java.util.List
import cz.gelion.shylock.invoice.entity.Subject
import java.util.ArrayList
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.ajax.markup.html.AjaxLink
import org.apache.wicket.markup.html.link.BookmarkablePageLink
import org.apache.wicket.request.mapper.parameter.PageParameters
import org.apache.wicket.ajax.AjaxRequestTarget
import org.apache.wicket.model.Model 
import cz.gelion.shylock.invoice.web.comp.AjaxDefferedLink

class SubjectListPage extends ShylockInvoicePage {

  def name = "subjectList"
  
    
  val subjectListCont = new WebMarkupContainer("subjectListCont")
  subjectListCont.setOutputMarkupId(true)
  add(subjectListCont)  
  val subjectListModel = new LoadableDetachableModel[List[Subject]] {
	  override def load:List[Subject] = {
	    log.trace("subjectListModel.load")
	    em.createQuery("select s from Subject s", classOf[Subject]).getResultList;
	  }
  }
  
  subjectListCont.add(new ListView[Subject]("subjectList", subjectListModel) {
	  override def populateItem(item:ListItem[Subject]) = {
	    val a = new BookmarkablePageLink("link.subject", classOf[SubjectPage], new PageParameters().add(SubjectPage.SUBJECT, item.getModelObject().getId))
	    item.add(a)
	    a.add(new Label("name", item.getModelObject.label))
	    item.add(new AjaxDefferedLink("link.remove", () => {"opravdu?"}) {
	      override def onClick(target:AjaxRequestTarget) = {
	        log.trace("removing: " + item.getModelObject)
	        em.getTransaction.begin
	        em.remove(em.merge(item.getModelObject))
	        em.getTransaction.commit
	        subjectListCont.detach
	        target.add(subjectListCont)
	      }
	    })
	  }
  })
  
  add(new AjaxLink("link.new") {
    override def onClick(target:AjaxRequestTarget) = {
      log.trace("AjaxLink[link.new]:onClick(" + target + ")")
      var subj = new Subject
      openModal(target, 
        new SubjectEditorPanel(modalContentId, new LoadableDetachableModel[Subject] {
           override def load:Subject = subj
        }, 
        submit=(s:Subject)=> {log.trace("submitted: " + s); subj = s}), 
        (t:AjaxRequestTarget) => {
          if (subj.getId > 0) setResponsePage(classOf[SubjectPage], new PageParameters().add(SubjectPage.SUBJECT, subj.getId))
        })
    }
  })
}